/*
 * @author java_deng
 * @date 2025/1/24 15:34
 * @description
 */
package org.kaka.service.impl;

import org.kaka.dto.PostDto;
import org.kaka.mapper.CommentMapper;
import org.kaka.mapper.PostMapper;
import org.kaka.po.CommentPo;
import org.kaka.vo.CommentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private PostMapper postMapper;

    @Transactional
    public void save(CommentVo commentVo) {
        Long postId = commentVo.getPostId();
        PostDto postDto1 = postMapper.selectById(postId);

        PostDto postDto = new PostDto();
        postDto.setId(postId);
        postDto.setCommentCount(postDto1.getCommentCount()+1);
        postMapper.updateById(postDto);

        commentVo.setIsDeleted(1);
        commentVo.setLikeCount(0);
        commentMapper.insert(commentVo);
    }

    public List<CommentVo> list(CommentPo commentPo) {
        List<CommentVo> data = commentMapper.list(commentPo);
        List<CommentVo> parentCommentVoList= data.stream().filter(item->item.getParentId()==0).collect(Collectors.toList());
        for(CommentVo commentVo:parentCommentVoList){
            commentVo.setChildComments(new ArrayList<>());
        }

        Map<Long, List<CommentVo>> parentCommentMap = parentCommentVoList.stream().collect(Collectors.toMap(CommentVo::getId, CommentVo::getChildComments));

        for(CommentVo commentVo: data){
            if(commentVo.getParentId()!=0){
                List<CommentVo> commentVoList = parentCommentMap.get(commentVo.getParentId());
                commentVoList.add(commentVo);
            }
        }
        return parentCommentVoList;
    }
}
